<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\record\controller;

use cmf\controller\AdminBaseController;
use app\dynamic\model\InfoModel;
use app\admin\model\ThemeModel;
use app\download\model\CateModel;

use think\Db;


class AdminRecordController extends AdminBaseController
{
    /**
     * 网站浏览记录列表
     * @adminMenu(
     *     'name'   => '网站浏览记录列表',
     *     'parent' => 'record/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '网站浏览记录列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $where   = [];
        $request = input('request.');
//
//        $where['type'] = 'webnews';
//
//        if (!empty($request['category'])) {
//            $where['cid'] = intval($request['category']);
//        }
//
//        $keywordComplex = [];
//        if (!empty($request['keyword'])) {
//            $keyword = $request['keyword'];
//
//            $keywordComplex['title|author']    = ['like', "%$keyword%"];
//        }

        $keywordComplex = array();

        $usersQuery = Db::name('ip_info');
        $list = $usersQuery->whereOr($keywordComplex)->where($where)->order("ctime DESC")->paginate(10);
        //echo $usersQuery->getLastSql();exit;
        // 获取分页显示
        $page = $list->render();


//        $cate_where['type'] =  'webnews';
//        $cate_where['isopen'] =  1;
//        $cateQuery = Db::name('cate');
//        $catelist = $cateQuery->whereOr(array())->where($cate_where)->order("ctime DESC")->select();
//        if(count($catelist)){
//            foreach ($catelist as  $v){
//                $newarr[$v['id']] = $v['name'];
//            }
//            $this->assign('catearr', $newarr);
//        }
//
//        $this->assign('keyword', isset($request['keyword']) ? $request['keyword'] : '');
//        $this->assign('category', isset($request['category']) ? $request['category'] : 0);
//        $this->assign('catelist', $catelist);
        $this->assign('list', $list);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }



    /**
     * 添加文章
     * @adminMenu(
     *     'name'   => '添加文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $themeModel        = new ThemeModel();
        $articleThemeFiles = $themeModel->getActionThemeFiles('dynamic/Dynamic/index');

        $cate_where['type'] =  'webnews';
        $cate_where['isopen'] =  1;
        $cateQuery = Db::name('cate');
        $catelist = $cateQuery->whereOr(array())->where($cate_where)->order("ctime DESC")->select();
        if(count($catelist)){
            $this->assign('catelist', $catelist);
        }
        $this->assign('article_theme_files', $articleThemeFiles);
        return $this->fetch();
    }


    /**
     * 添加文章提交
     * @adminMenu(
     *     'name'   => '添加文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加文章提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {

            $data   = $this->request->param();

            $InfoModel = new InfoModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['path']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['path']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['attachment']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['attachment']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $data['post']['ctime'] = strtotime($data['post']['ctime']);
            $InfoModel->adminAddInfo($data['post']);
            $this->success('添加成功!', url('AdminDynamic/edit', ['id' => $InfoModel->id]));
        }

    }

    /**
     * 编辑/添加 公告
     * @adminMenu(
     *     'name'   => '编辑/添加 公告',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑/添加 公告',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id > 0) {
            $category = InfoModel::get($id)->toArray();
            $this->assign("post",$category);
        }
        $cate_where['type'] =  'news';
        $cate_where['isopen'] =  1;
        $cateQuery = Db::name('cate');
        $catelist = $cateQuery->whereOr(array())->where($cate_where)->order("ctime DESC")->select();
        if(count($catelist)){
            $this->assign('catelist', $catelist);
        }
        return $this->fetch();
    }

    /**
     * 编辑文章提交
     * @adminMenu(
     *     'name'   => '编辑文章提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data   = $this->request->param();

            $InfoModelModel = new InfoModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $InfoModelModel->adminEditArticle($data['post'], $data['post']['categories']);


            $this->success('保存成功!');

        }
    }

    /**
     * 文章分类选择对话框
     * @adminMenu(
     *     'name'   => '文章分类选择对话框',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章分类选择对话框',
     *     'param'  => ''
     * )
     */
    public function select()
    {
        $ids                 = $this->request->param('ids');
        $selectedIds         = explode(',', $ids);
        $portalCategoryModel = new CateModel();

        $tpl = <<<tpl
<tr class='data-item-tr'>
    <td>
        <input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]'
               value='\$id' data-name='\$name' \$checked>
    </td>
    <td>\$id</td>
    <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
</tr>
tpl;

        $categoryTree = $portalCategoryModel->adminCategoryTableTree($selectedIds, $tpl);
        $where      = ['delete_time' => 0];
        $categories = $portalCategoryModel->where($where)->select();
        $this->assign('categories', $categories);
        $this->assign('selectedIds', $selectedIds);
        $this->assign('categories_tree', $categoryTree);
        return $this->fetch();
    }

    /**
     * 文章分类排序
     * @adminMenu(
     *     'name'   => '文章分类排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章分类排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders(Db::name('portal_category'));
        $this->success("排序更新成功！", '');
    }

    /**
     * 删除文章分类
     * @adminMenu(
     *     'name'   => '删除文章分类',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除文章分类',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $portalCategoryModel = new PortalCategoryModel();
        $id                  = $this->request->param('id');
        //获取删除的内容
        $findCategory = $portalCategoryModel->where('id', $id)->find();
        if (empty($findCategory)) {
            $this->error('分类不存在!');
        }
        $categoryChildrenCount = $portalCategoryModel->where('parent_id', $id)->count();
        if ($categoryChildrenCount > 0) {
            $this->error('此分类有子类无法删除!');
        }
        $categoryPostCount = Db::name('portal_category_post')->where('category_id', $id)->count();

        if ($categoryPostCount > 0) {
            $this->error('此分类有文章无法删除!');
        }
        $data   = [
            'object_id'   => $findCategory['id'],
            'create_time' => time(),
            'table_name'  => 'portal_category',
            'name'        => $findCategory['name']
        ];
        $result = $portalCategoryModel
            ->where('id', $id)
            ->update(['delete_time' => time()]);
        if ($result) {
            Db::name('recycleBin')->insert($data);
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }
}
